#include "simpleoperation.h"
#include "QPushButton"
#include "math.h"

void qDebug(float num)
{
	char* str = new char[30];
	sprintf(str, "%f", num ); 
	qDebug(str);
}

SimpleOperation::SimpleOperation(QWidget *parent, PBO* pbo, SIMPLE_OPER oper, int min, int max, float step, int startValue)
	: QWidget(parent)
{
	ui.setupUi(this);
	this->operation = oper;
	this->pbo = pbo;

	this->setFixedSize(180, 100);

	QPushButton* buttonOK = new QPushButton("OK", this);
	buttonOK->move(20,70);

	QObject::connect(buttonOK,SIGNAL(clicked()), this,SLOT(OK_clicked()));

	QPushButton* cancelOK = new QPushButton("Cancel", this);
	cancelOK->move(100,70);

	QObject::connect(cancelOK,SIGNAL(clicked()), this,SLOT(close()));


	param = new QSlider(this);

	factor = 1 / step;
	
	param->setRange(min * factor, max * factor);
	param->setFixedSize(150, 15);
    param->setSingleStep(1);
    param->setValue(startValue * factor);
	param->setOrientation(Qt::Orientation::Horizontal);
	param->move(10,10);

	QObject::connect(param,SIGNAL(valueChanged(int)), this,SLOT(ParamValueChanged(int)));

	edit = new QLineEdit(this);
	edit->move(10,40);
	edit->setText(QString().number(startValue));
	edit->setDisabled(true);

}

void SimpleOperation::run(bool pernam)
{
	qDebug(value);
	if(operation == LINEAR_FILTER || operation == GAUSS_FILTER)
	{
		int size = value * 2 + 1;

		float* table = new float[size*size];
		for(int c=0;c<size;c++)
		{
			for(int r=0;r<size;r++)
			{
				if(operation == LINEAR_FILTER) table[c + r*size] = 1.0;
				else
				{
					float sig = (float)size / 5;
					float e = 2.718;
					float pi = 3.14;
					float ulam = (1 / ( 2 * pi * pow(sig,(float)2) ));
					float wykl = (pow((c-value),(float)2)   +   pow((r-value),(float)2))    /   (2*pow(sig,(float)2));
					table[c + r*size] = ulam * pow(e, -1 * wykl);
				}
			}
		}
		pbo->convolution(table, size, pernam);
	}
	else if(operation == MEDIANA)
	{
		pbo->mediana(value*2+1, pernam);
	}
	else
	{
		pbo->simpleOperation(operation, value, pernam);
	}
}


void SimpleOperation::ParamValueChanged(int i)
{
	this->value = (float)i / factor;
	edit->setText(QString().number(this->value));
	run(false);
}

void SimpleOperation::OK_clicked()
{
	run(true);
	QWidget::close();
	this->deleteLater();
}

void SimpleOperation::close()
{
	pbo->identity();
	QWidget::close();
	this->deleteLater();
}


SimpleOperation::~SimpleOperation()
{

}
